package com.jt.assistant.ui

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.dothantech.lpapi.LPAPI
import com.dothantech.printer.IDzPrinter
import com.gengcon.www.jcprintersdk.JCAPI
import com.gengcon.www.jcprintersdk.callback.Callback
import com.gengcon.www.jcprintersdk.callback.PrintCallback
import com.jt.assistant.R
import com.jt.assistant.bean.BtStatus
import com.jt.assistant.bean.CartonResponseBean
import com.jt.assistant.bean.Param
import com.jt.assistant.utils.B11PrinterHelper
import com.jt.assistant.utils.B21PrinterHelper
import com.jt.assistant.viewmodel.HomeViewModel
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_printer.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 箱码打印
 */
class PrinterActivity : BaseActivity<HomeViewModel>() {
    private var mCurrentPrinter = ""
    private var mCurrentPrinterBean: BtStatus? = null
    private val mBtAdapter: BluetoothAdapter by lazy {
        BluetoothAdapter.getDefaultAdapter()
    }
    private var mB11PrintApi: LPAPI? = null

    private var mB21Printer: JCAPI? = null

    private var isShowToast: Boolean = true


    override fun onResume() {
        super.onResume()
        isShowToast = true

        mCurrentPrinter = MMKV.defaultMMKV().getString("CURRENT_PRINTER", "").toString()


        if (!mBtAdapter.isEnabled) {
            //蓝牙未打开
            showTipDialog("当前未连接打印机,请点击确定设置蓝牙打印机")
            return
        }

        if (mCurrentPrinter.isEmpty()) {
            //未连接打印机
            showTipDialog("当前未连接打印机,请点击确定设置蓝牙打印机")
            return
        } else {
            mCurrentPrinterBean = GsonUtils.fromJson(mCurrentPrinter, BtStatus::class.java)
        }


        if (mCurrentPrinterBean!!.name.contains("B11")) {
            //B11
            mB11PrintApi = LPAPI.Factory.createInstance(mB11Callback)
        } else {
            //B21
            mB21Printer = JCAPI.getInstance(initCallback())
        }

        if (!isPrinterConnected()) {
            GlobalScope.launch {
                delay(500)
                //连接打印机
                connectPrinter()
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        //断开打印机
        isShowToast = false
        closePrinter()
    }

    override fun layoutId(): Int = R.layout.activity_printer

    override fun initView(savedInstanceState: Bundle?) {

    }

    override fun initData() {


    }

    override fun initListener() {
        top_bar.mTvRightTitle.setOnClickListener {
            isShowToast = false
            closePrinter()
            startActivity(Intent(this, BluetoothActivity::class.java))
        }

        bt_commit.setOnClickListener {
            if (ie_channelOrderNo.mEdit.text.isNullOrEmpty() || ie_cartonCode.mEdit.text.isNullOrEmpty()) {
                ToastUtils.showShort("未完成输入")
                return@setOnClickListener
            }

            if (mCurrentPrinter.isEmpty()) {
                ToastUtils.showShort("请先设置打印机")
                return@setOnClickListener
            }

            //判断是否连接上打印机
            if (!isPrinterConnected()) {
                ToastUtils.showShort("打印机未连接,请检查打印机是否开启")
                return@setOnClickListener
            }

            val params = Param::class.java.newInstance()
            params.cartonCode = ie_cartonCode.mEdit.text.toString()
            viewModel.getReturnsCartonDetail(params)
        }

        viewModel.mGetReturnsCartonDetail.observe(this, {
            if (it.isSuccess()) {
                printCode(it.data)
            } else {
                Logger.e("printBarcode")
                printBarcode()
            }
        })
    }


    private fun closePrinter() {
        if (mCurrentPrinterBean != null)
            GlobalScope.launch {
                if (mCurrentPrinterBean!!.name.contains("B11")) {
                    if (mB11PrintApi != null) mB11PrintApi!!.quit()
                } else {
                    if (mB21Printer != null) mB21Printer!!.close()
                }
            }
    }

    private fun connectPrinter() {
        if (mCurrentPrinterBean!!.name.contains("B11")) {
            //B11
            mB11PrintApi!!.openPrinterByAddress(
                IDzPrinter.PrinterAddress(
                    mCurrentPrinterBean!!.name,
                    mCurrentPrinterBean!!.address,
                    IDzPrinter.AddressType.SPP
                )
            )
        } else {
            //B21
            initPrintCallback()
            mB21Printer!!.openPrinterByAddress(
                application, mCurrentPrinterBean!!.address, 0
            )
        }
    }


    private fun isPrinterConnected(): Boolean {
        if (mCurrentPrinterBean!!.name.contains("B11")) {
            //B11
            val state = mB11PrintApi!!.printerState
            // 打印机未连接
            if (state == null || state == IDzPrinter.PrinterState.Disconnected || state == IDzPrinter.PrinterState.Connecting) {
                return false
            }
        } else {
            //B21打印机
            if (mB21Printer!!.isConnection != 0) {
                return false
            }
        }
        // 打印机已连接
        return true
    }

    private fun showTipDialog(text: String) {
        MaterialDialog(this).show {
            title(text = text)
            positiveButton(text = "确定") {
                startActivity(Intent(this@PrinterActivity, BluetoothActivity::class.java))
            }
            negativeButton(text = "取消") {}
            lifecycleOwner(this@PrinterActivity)
        }
    }

    private fun printCode(data: CartonResponseBean) {
        if (mCurrentPrinterBean!!.name.contains("B11")) {
            B11PrinterHelper.B11PrintData(mB11PrintApi, data)
        } else {//B21打印机
            B21PrinterHelper.B21PrintData(mB21Printer, data, true)
            mB21Printer!!.commitJob(1, 1, 3, mB21PrintCallback)
        }
    }

    private fun printBarcode() {
        if (mCurrentPrinterBean!!.name.contains("B21")) {
            B21PrinterHelper.printBarcode(
                mB21Printer,
                ie_channelOrderNo.mEdit.text.toString(),
                ie_cartonCode.mEdit.text.toString(),
            )
            mB21Printer!!.commitJob(1, 1, 3, mB21PrintCallback)

        } else {//B11打印机
            B11PrinterHelper.printBarcode(
                mB11PrintApi,
                ie_channelOrderNo.mEdit.text.toString(),
                ie_cartonCode.mEdit.text.toString(),
            )
        }
    }


    private val mB11Callback: LPAPI.Callback = object : LPAPI.Callback {
        // 打印机连接状态发生变化时被调用
        override fun onStateChange(arg0: IDzPrinter.PrinterAddress, arg1: IDzPrinter.PrinterState) {
            runOnUiThread {
                when (arg1) {
                    IDzPrinter.PrinterState.Connected, IDzPrinter.PrinterState.Connected2 -> {
                        ToastUtils.showShort("打印机连接成功")
                    }
                    IDzPrinter.PrinterState.Disconnected -> {
                        if (isShowToast)
                            speakString("打印机连接失败")
                    }
                    else -> {
                    }
                }
            }

        }

        // 蓝牙适配器状态发生变化时被调用
        override fun onProgressInfo(arg0: IDzPrinter.ProgressInfo, arg1: Any) {}
        override fun onPrinterDiscovery(
            arg0: IDzPrinter.PrinterAddress,
            arg1: IDzPrinter.PrinterInfo
        ) {

        }

        // 打印标签的进度发生变化是被调用
        override fun onPrintProgress(
            address: IDzPrinter.PrinterAddress,
            bitmapData: Any,
            progress: IDzPrinter.PrintProgress,
            addiInfo: Any
        ) {
            runOnUiThread {
                when (progress) {
                    IDzPrinter.PrintProgress.Success -> {
                        speakString("封箱成功")
                        ie_channelOrderNo.mEdit.setText("")
                        ie_cartonCode.mEdit.setText("")
                    }
                    IDzPrinter.PrintProgress.Failed -> {
                        speakString("封箱失败,检查是否缺纸")
                    }
                    else -> {
                    }
                }
            }
        }
    }


    private var mB21PrintCallback: PrintCallback? = null
    private fun initPrintCallback() {
        mB21PrintCallback = object : PrintCallback {
            override fun onPrintProgress(i: Int) {
                //打印精度回调
            }

            override fun onPrintPageCompleted() {
                //页打印完成回调
                runOnUiThread {
                    speakString("封箱成功")
                    mB21Printer!!.endJob()
                    ie_channelOrderNo.mEdit.setText("")
                    ie_cartonCode.mEdit.setText("")
                }

            }

            override fun onRibbonUsed(v: Double) {
                //碳带使用长度上报
            }

            override fun onPageNumberReceivingTimeout() {
                //页码接收超时

            }

            override fun onAbnormalResponse(i: Int) {
                runOnUiThread {
                    //打印异常回调,部分回调需要调用结束打印
                    if (i > 24) return@runOnUiThread
                    mB21Printer!!.endJob()
                    speakString("打印机异常,请检查打印机")
                }
            }
        }
    }

    private fun initCallback(): Callback? {

        /*
         * 创建全局回调
         */
        return object : Callback {
            override fun onConnectSuccess(s: String, i: Int) {
                //打印机连接成功
                runOnUiThread {
                    ToastUtils.showShort("打印机连接成功")
                }

            }

            override fun onDisConnect() {
                //打印机断开及连接失败回调 （SDK内部无广播。关闭打印机及关闭蓝牙此处不会回调。需要实时监听状态 需要用到蓝牙广播）
                runOnUiThread {
                    if (isShowToast)
                        speakString("打印机连接失败")
                }

            }

            override fun onElectricityChange(i: Int) {

                //打印机电量变化
            }

            override fun onCoverStatus(i: Int) {
                //打印机上盖状态监听
                if (i == 0) showMainToast("打印机开盖")
            }

            override fun onPaperStatus(i: Int) {
                //打印机标签装入状态监听
                //打印机标签装入状态监听
                if (i == 1) showMainToast("打印机缺纸")
            }

            override fun onHeartDisConnect() {
                //心跳断开，此处应调用断开打印机
                mB21Printer!!.close()
            }
        }
    }

    private fun showMainToast(string: String) {
        runOnUiThread {
            speakString(string)
            showTip(string)
        }
    }

    private var dialog: MaterialDialog? = null
    private fun showTip(tip: String) {
        if (dialog != null && dialog!!.isShowing) dialog!!.dismiss()
        dialog = MaterialDialog(this).show {
            title(text = tip)
            positiveButton(text = "确定")
            lifecycleOwner(this@PrinterActivity)
        }
    }
}